<!DOCTYPE html>
<meta charset="utf-8">
<title>A股收盘概览</title>
<link rel="stylesheet" type="text/css" href="style.css" />
<script src="https://d3js.org/d3.v2.js"></script>
<script src="https://code.jquery.com/jquery-1.7.1.js"></script>
<h2>A股收盘概览</h2>
<p>大小表示成交额，颜色表示涨跌幅，点击以进入，点击最上方长条以返回上级</p>
<br> Date (yyyy-MM-dd):
<input type="text" id="dateInput" value="2018-03-06">
<input type="button" onclick="showTreeMap();" value="Refresh">
<p id="chart">
<p id="rawdata">

<script src="treemap.js"></script>
<script>

    function getQueryParam(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]); return null;
    }

	function reSortRoot(root,value_key) {
		//console.log("Calling");
		for (var key in root) {
			if (key == "key") {
				root.name = root.key;
				delete root.key;
			}
			if (key == "values") {
				root.children = [];
				for (item in root.values) {
					root.children.push(reSortRoot(root.values[item],value_key));
				}
				delete root.values;
			}
			if (key == value_key) {
				root.value = parseFloat(root[value_key]);
				delete root[value_key];
			}
		}
		return root;
	}

	function showTreeMap()  {
		// You can comment out the whole csv section if you just have a JSON file.
    // loadJSONFile('data/portaldata.json');
        date=getQueryParam('date');
        date = document.getElementById("dateInput").value;
        if(!date){
            var nowDate = new Date();
            var nowMonth = nowDate.getMonth() + 1;
            var strDate = nowDate.getDate();
           

            // 对月份进行处理，1-9月在前面添加一个“0”
            if (nowMonth >= 1 && nowMonth <= 9) {
               nowMonth = "0" + nowMonth;
            }

            // 对日进行处理，1-9号在前面添加一个“0”
            if (strDate >= 0 && strDate <= 9) {
               strDate = "0" + strDate;
            }

            // 最后拼接字符串，得到一个格式为(yyyy-MM-dd)的日期
            date = nowDate.getFullYear() + "-" + nowMonth + "-" + strDate;

        }


    	d3.csv("https://raw.githubusercontent.com/fanjingdan012/stock-crawler/master/static/industry_quote/"+date+".csv", function(csv_data){

			// Add, remove or change the key values to change the hierarchy. 
      var nested_data = d3.nest()
                    .key(function(d)  { return d.industry1_name; })
       				.key(function(d)  { return d.industry2_name; })
       				.key(function(d)  { return d.name; })
				      .entries(csv_data);
			
			// Creat the root node for the treemap
			var root = {};
			
			// Add the data to the tree
			root.key = "Data";
			root.values = nested_data;
		
			// Change the key names and children values from .next and add values for a chosen column to define the size of the blocks
			root = reSortRoot(root,"amount");
			
			// DEBUG
// 			$("#rawdata").html(JSON.stringify(root));
			
			loadData(root);
			
		});


	}
</script>